<template>
  <div class="notifications-container">
    <el-card class="header-card">
      <div class="header-content">
        <h2>📨 通知管理</h2>
        <el-button type="primary" @click="showCreateDialog">
          <el-icon><Plus /></el-icon>
          创建通知
        </el-button>
      </div>
    </el-card>

    <!-- 通知列表 -->
    <el-card class="table-card">
      <el-table :data="notifications" style="width: 100%">
        <el-table-column label="标题" prop="title" min-width="200" />
        
        <el-table-column label="内容" prop="content" min-width="250">
          <template #default="{ row }">
            <div class="content-preview">{{ row.content }}</div>
          </template>
        </el-table-column>

        <el-table-column label="类型" width="100">
          <template #default="{ row }">
            <el-tag :type="getTypeColor(row.type)" size="small">
              {{ getTypeLabel(row.type) }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column label="优先级" width="100">
          <template #default="{ row }">
            <el-tag :type="getPriorityColor(row.priority)" size="small">
              {{ getPriorityLabel(row.priority) }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column label="目标" width="120">
          <template #default="{ row }">
            <el-tag size="small">{{ getTargetLabel(row.target_type) }}</el-tag>
          </template>
        </el-table-column>

        <el-table-column label="阅读状态" width="150">
          <template #default="{ row }">
            <div class="read-stats">
              <span class="read">已读: {{ row.read_count || 0 }}</span>
              <span class="unread">未读: {{ row.unread_count || 0 }}</span>
            </div>
          </template>
        </el-table-column>

        <el-table-column label="创建时间" width="160">
          <template #default="{ row }">
            {{ formatTime(row.created_at) }}
          </template>
        </el-table-column>

        <el-table-column label="操作" width="150" fixed="right">
          <template #default="{ row }">
            <el-button link type="primary" size="small" @click="viewDetail(row)">
              详情
            </el-button>
            <el-button link type="danger" size="small" @click="deleteNotification(row.id)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="loadNotifications"
          @current-change="loadNotifications"
        />
      </div>
    </el-card>

    <!-- 创建通知对话框 -->
    <el-dialog
      v-model="createDialogVisible"
      title="创建通知"
      width="600px"
      :close-on-click-modal="false"
    >
      <el-form :model="form" :rules="rules" ref="formRef" label-width="100px">
        <el-form-item label="标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入通知标题" />
        </el-form-item>

        <el-form-item label="内容" prop="content">
          <el-input
            v-model="form.content"
            type="textarea"
            :rows="4"
            placeholder="请输入通知内容"
          />
        </el-form-item>

        <el-form-item label="类型" prop="type">
          <el-radio-group v-model="form.type">
            <el-radio label="text">纯文字</el-radio>
            <el-radio label="image">图片</el-radio>
            <el-radio label="both">图文</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="图片URL" v-if="form.type !== 'text'">
          <el-input v-model="form.imageUrl" placeholder="请输入图片URL（可选）" />
        </el-form-item>

        <el-form-item label="优先级" prop="priority">
          <el-select v-model="form.priority" placeholder="选择优先级">
            <el-option label="低" value="low" />
            <el-option label="普通" value="normal" />
            <el-option label="高" value="high" />
            <el-option label="紧急" value="urgent" />
          </el-select>
        </el-form-item>

        <el-form-item label="目标类型" prop="targetType">
          <el-select v-model="form.targetType" placeholder="选择目标类型" @change="handleTargetTypeChange">
            <el-option label="所有用户" value="all" />
            <el-option label="特定用户" value="user" />
            <el-option label="特定客户端" value="client" />
          </el-select>
        </el-form-item>

        <el-form-item label="目标" v-if="form.targetType === 'user'" prop="targetIds">
          <el-select
            v-model="form.targetIds"
            multiple
            filterable
            placeholder="选择目标用户"
            style="width: 100%"
          >
            <el-option
              v-for="user in users"
              :key="user.id"
              :label="`${user.username} (${user.nickname || 'N/A'})`"
              :value="user.id.toString()"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="目标" v-if="form.targetType === 'client'" prop="targetIds">
          <el-select
            v-model="form.targetIds"
            multiple
            filterable
            placeholder="选择目标客户端"
            style="width: 100%"
          >
            <el-option
              v-for="client in clients"
              :key="client.client_id"
              :label="`${client.hostname} (${client.platform})`"
              :value="client.client_id"
            />
          </el-select>
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="createDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleCreate">创建</el-button>
      </template>
    </el-dialog>

    <!-- 详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="通知详情"
      width="800px"
    >
      <div v-if="selectedNotification" class="detail-content">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="标题">
            {{ selectedNotification.title }}
          </el-descriptions-item>
          <el-descriptions-item label="类型">
            <el-tag :type="getTypeColor(selectedNotification.type)" size="small">
              {{ getTypeLabel(selectedNotification.type) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="优先级">
            <el-tag :type="getPriorityColor(selectedNotification.priority)" size="small">
              {{ getPriorityLabel(selectedNotification.priority) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="目标类型">
            {{ getTargetLabel(selectedNotification.target_type) }}
          </el-descriptions-item>
          <el-descriptions-item label="发送者">
            {{ selectedNotification.sender_name || 'System' }}
          </el-descriptions-item>
          <el-descriptions-item label="创建时间">
            {{ formatTime(selectedNotification.created_at) }}
          </el-descriptions-item>
          <el-descriptions-item label="内容" :span="2">
            {{ selectedNotification.content }}
          </el-descriptions-item>
          <el-descriptions-item label="图片" :span="2" v-if="selectedNotification.image_url">
            <img :src="selectedNotification.image_url" style="max-width: 400px" />
          </el-descriptions-item>
        </el-descriptions>

        <h3 style="margin-top: 20px">阅读记录</h3>
        <el-table :data="readRecords" style="width: 100%" max-height="300">
          <el-table-column label="用户" prop="username" width="120" />
          <el-table-column label="客户端" prop="hostname" width="150" />
          <el-table-column label="状态" width="80">
            <template #default="{ row }">
              <el-tag :type="row.is_read ? 'success' : 'warning'" size="small">
                {{ row.is_read ? '已读' : '未读' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="阅读时间" width="160">
            <template #default="{ row }">
              {{ formatTime(row.read_at) }}
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import api from '@/api'

// 响应式数据
const notifications = ref([])
const users = ref([])
const clients = ref([])
const readRecords = ref([])
const selectedNotification = ref(null)
const createDialogVisible = ref(false)
const detailDialogVisible = ref(false)
const formRef = ref(null)

const pagination = reactive({
  page: 1,
  pageSize: 20,
  total: 0
})

const form = reactive({
  title: '',
  content: '',
  type: 'text',
  imageUrl: '',
  priority: 'normal',
  targetType: 'all',
  targetIds: []
})

const rules = {
  title: [{ required: true, message: '请输入标题', trigger: 'blur' }],
  content: [{ required: true, message: '请输入内容', trigger: 'blur' }],
  targetType: [{ required: true, message: '请选择目标类型', trigger: 'change' }],
  targetIds: [
    {
      validator: (rule, value, callback) => {
        if (form.targetType !== 'all' && (!value || value.length === 0)) {
          callback(new Error('请选择目标'))
        } else {
          callback()
        }
      },
      trigger: 'change'
    }
  ]
}

// 加载通知列表
const loadNotifications = async () => {
  try {
    const response = await api.get('/api/notifications/admin/all', {
      params: {
        page: pagination.page,
        pageSize: pagination.pageSize
      }
    })

    if (response.data.success) {
      notifications.value = response.data.data.notifications || []
      pagination.total = response.data.data.total || 0
    } else {
      ElMessage.error(response.data.message || '加载通知列表失败')
      notifications.value = []
    }
  } catch (error) {
    const errorMsg = error.response?.data?.message || error.message || '加载通知列表失败'
    ElMessage.error(errorMsg)
    console.error('加载通知列表错误:', error)
    console.error('错误详情:', error.response?.data)
    notifications.value = []
  }
}

// 加载用户列表
const loadUsers = async () => {
  try {
    const response = await api.get('/api/users', {
      params: { page: 1, pageSize: 1000 }
    })
    if (response.data.success) {
      users.value = response.data.data.users
    }
  } catch (error) {
    console.error('加载用户列表失败:', error)
  }
}

// 加载客户端列表（仅显示在线的客户端）
const loadClients = async () => {
  try {
    const response = await api.get('/api/clients', {
      params: { 
        page: 1, 
        pageSize: 1000,
        online: 1  // 只显示在线的客户端
      }
    })
    if (response.data.success) {
      clients.value = response.data.data.clients
    }
  } catch (error) {
    console.error('加载客户端列表失败:', error)
  }
}

// 显示创建对话框
const showCreateDialog = () => {
  resetForm()
  createDialogVisible.value = true
}

// 处理目标类型变化
const handleTargetTypeChange = () => {
  form.targetIds = []
}

// 创建通知
const handleCreate = async () => {
  try {
    await formRef.value.validate()

    const data = {
      title: form.title,
      content: form.content,
      type: form.type,
      imageUrl: form.imageUrl || null,
      priority: form.priority,
      targetType: form.targetType,
      targetIds: form.targetType === 'all' ? null : form.targetIds
    }

    const response = await api.post('/api/notifications', data)

    if (response.data.success) {
      ElMessage.success('通知创建成功')
      createDialogVisible.value = false
      loadNotifications()
    }
  } catch (error) {
    if (error.response) {
      ElMessage.error(error.response.data.message || '创建通知失败')
    } else {
      ElMessage.error('表单验证失败')
    }
  }
}

// 查看详情
const viewDetail = async (notification) => {
  selectedNotification.value = notification
  detailDialogVisible.value = true

  // 加载阅读记录
  try {
    const response = await api.get(`/api/notifications/admin/${notification.id}/reads`)
    if (response.data.success) {
      readRecords.value = response.data.data.reads
    }
  } catch (error) {
    console.error('加载阅读记录失败:', error)
  }
}

// 删除通知
const deleteNotification = async (id) => {
  try {
    await ElMessageBox.confirm('确定要删除这条通知吗？', '确认删除', {
      type: 'warning'
    })

    const response = await api.delete(`/api/notifications/${id}`)
    if (response.data.success) {
      ElMessage.success('删除成功')
      loadNotifications()
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

// 重置表单
const resetForm = () => {
  form.title = ''
  form.content = ''
  form.type = 'text'
  form.imageUrl = ''
  form.priority = 'normal'
  form.targetType = 'all'
  form.targetIds = []
}

// 格式化时间
const formatTime = (time) => {
  if (!time) return '-'
  const date = new Date(time)
  return date.toLocaleString('zh-CN')
}

// 获取类型标签
const getTypeLabel = (type) => {
  const map = {
    text: '文字',
    image: '图片',
    both: '图文'
  }
  return map[type] || type
}

// 获取类型颜色
const getTypeColor = (type) => {
  const map = {
    text: '',
    image: 'success',
    both: 'warning'
  }
  return map[type] || ''
}

// 获取优先级标签
const getPriorityLabel = (priority) => {
  const map = {
    low: '低',
    normal: '普通',
    high: '高',
    urgent: '紧急'
  }
  return map[priority] || priority
}

// 获取优先级颜色
const getPriorityColor = (priority) => {
  const map = {
    low: 'info',
    normal: '',
    high: 'warning',
    urgent: 'danger'
  }
  return map[priority] || ''
}

// 获取目标类型标签
const getTargetLabel = (targetType) => {
  const map = {
    all: '所有用户',
    user: '特定用户',
    client: '特定客户端'
  }
  return map[targetType] || targetType
}

// 初始化
onMounted(() => {
  loadNotifications()
  loadUsers()
  loadClients()
})
</script>

<style scoped>
.notifications-container {
  padding: 20px;
}

.header-card {
  margin-bottom: 20px;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-content h2 {
  margin: 0;
  font-size: 24px;
  color: #303133;
}

.table-card {
  min-height: 600px;
}

.content-preview {
  max-width: 250px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.read-stats {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.read-stats .read {
  color: #67c23a;
  font-size: 12px;
}

.read-stats .unread {
  color: #e6a23c;
  font-size: 12px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.detail-content {
  max-height: 600px;
  overflow-y: auto;
}
</style>
